﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Collections;
using System.Data;

namespace Common
{
    /// <summary>
    /// JSONHelper 的摘要说明
    /// </summary>
    public class JsonHelper
    {
        //对应JSON的singleInfo成员
        public string singleInfo = string.Empty;

        protected string _error = string.Empty;
        protected bool _success = true;
        protected long _totalCount = 0;
        protected System.Collections.ArrayList arrData = new ArrayList();
        protected System.Collections.ArrayList arrDataItem = new ArrayList();
        //protected System.Collections.ArrayList arrColumn = new ArrayList();
        //protected System.Collections.ArrayList arrField = new ArrayList();


        public JsonHelper()
        {

        }

        public  string ToJSON(object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public  string ToJSON(object obj, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);
        }

        //对应于JSON的success成员
        public bool success
        {
            get
            {
                return _success;
            }
            set
            {
                //如设置为true则清空error
                if (success) _error = string.Empty;
                _success = value;
            }
        }

        //对应于JSON的error成员
        public string error
        {
            get
            {
                return _error;
            }
            set
            {
                //如设置error，则自动设置success为false
                if (value != "") _success = false;
                _error = value;
            }
        }

        public long totlalCount
        {
            get { return _totalCount; }
            set { _totalCount = value; }
        }

        //重置，每次新生成一个json对象时必须执行该方法
        public void Reset()
        {
            _success = true;
            _error = string.Empty;
            singleInfo = string.Empty;
            arrData.Clear();
            arrDataItem.Clear();
            //arrColumn.Clear();
            //arrField.Clear();
        }

        public void AddItem(string name, string value)
        {
            arrData.Add("\"" + name + "\":" + "\"" + value + "\"");
        }

        //public void AddColumn(string name, string value)
        //{
        //    arrColumn.Add("\"" + name + "\":" + "\"" + value + "\"");
        //}

        //public void AddField(string name, string value)
        //{
        //    arrField.Add("\"" + name + "\":" + "\"" + value + "\"");
        //}

        public void ItemOk()
        {
            arrData.Add("<BR>");
        }

        //public void ColumnOk()
        //{
        //    arrColumn.Add("<BR>");
        //}

        //public void FieldOk()
        //{
        //    arrField.Add("<BR>");
        //}

        //序列化JSON对象，得到返回的JSON代码
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("totalCount:" + totlalCount.ToString() + ",");
            sb.Append("success:" + _success.ToString().ToLower() + ",");
            sb.Append("error:\"" + _error.Replace("\"", "\\\"") + "\",");
            sb.Append("singleInfo:\"" + singleInfo.Replace("\"", "\\\"") + "\",");
            sb.Append("data:[");

            int index = 0;
            sb.Append("{");
            if (arrData.Count <= 0)
            {
                //sb.Append("}],columModle:[");
                sb.Append("}]");
            }
            else
            {
                foreach (string val in arrData)
                {
                    index++;

                    if (val != "<BR>")
                    {
                        sb.Append(val + ",");
                    }
                    else
                    {
                        sb = sb.Replace(",", "", sb.Length - 1, 1);
                        sb.Append("},");
                        if (index < arrData.Count)
                        {
                            sb.Append("{");
                        }
                    }

                }
                sb = sb.Replace(",", "", sb.Length - 1, 1);
                //    sb.Append("],columModle:[");
                //}

                //index = 0;
                //sb.Append("{");
                //if (arrColumn.Count <= 0)
                //{
                //    sb.Append("}],fieldsNames:[");
                //}
                //else
                //{
                //    foreach (string val in arrColumn)
                //    {
                //        index++;

                //        if (val != "<BR>")
                //        {
                //            sb.Append(val + ",");
                //        }
                //        else
                //        {
                //            sb = sb.Replace(",", "", sb.Length - 1, 1);
                //            sb.Append("},");
                //            if (index < arrColumn.Count)
                //            {
                //                sb.Append("{");
                //            }
                //        }

                //    }
                //    sb = sb.Replace(",", "", sb.Length - 1, 1);
                //    sb.Append("],fieldsNames:[");
                //}

                //index = 0;
                //sb.Append("{");
                //if (arrField.Count <= 0)
                //{
                //    sb.Append("}]");
                //}
                //else
                //{
                //    foreach (string val in arrField)
                //    {
                //        index++;

                //        if (val != "<BR>")
                //        {
                //            sb.Append(val + ",");
                //        }
                //        else
                //        {
                //            sb = sb.Replace(",", "", sb.Length - 1, 1);
                //            sb.Append("},");
                //            if (index < arrField.Count)
                //            {
                //                sb.Append("{");
                //            }
                //        }

                //    }
                //    sb = sb.Replace(",", "", sb.Length - 1, 1);
                sb.Append("]");
            }

            sb.Append("}");
            return sb.ToString();
        }


        /// <summary>
        /// 删除结尾字符
        /// </summary>
        /// <param name="str">需要删除的字符</param>
        /// <returns>完成后的字符串 成功(JSON) 异常99998|信息</returns>
        private  string DeleteLast(string str)
        {
            try
            {
                if (str.Length > 1)
                {
                    return str.Substring(0, str.Length - 1);
                }
                return str;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Datatable转换为Json
        /// </summary>
        /// <param name="table">Datatable对象</param>
        /// <returns>Json字符串 成功(JSON) 异常99998|信息</returns>
        public string DatatableToJson(DataTable table)
        {
            try
            {
                string jsonString = "[";
                DataRowCollection drc = table.Rows;
                for (int i = 0; i < drc.Count; i++)
                {
                    jsonString += "{";
                    foreach (DataColumn column in table.Columns)
                    {
                        jsonString += "\"" + StringToJson(column.ColumnName) + "\":";
                        if (column.DataType == typeof(DateTime))
                        {
                            jsonString += "\"" + StringToJson(drc[i]

                           [column.ColumnName].ToString()) + "\",";
                        }
                        else if (column.DataType == typeof(string))
                        {
                            jsonString += "\"" + StringToJson(drc[i]

                            [column.ColumnName].ToString()) + "\",";
                        }
                        else
                        {
                            jsonString += "\"" + StringToJson(drc[i][column.ColumnName].ToString()) +

                            "\",";
                        }
                    }
                    jsonString = DeleteLast(jsonString) + "},";
                }
                return DeleteLast(jsonString) + "]";
            }
            catch (Exception ex)
            {

                return string.Empty;
            }
        }

       

        /// <summary>
        /// DataSet转换为Json
        /// </summary>
        /// <param name="dataSet">DataSet对象</param>
        /// <returns>Json字符串 成功(JSON) 异常99998|信息</returns>
        public string DataSetToJson(DataSet dataSet)
        {
            try
            {
                string jsonString = "{";
                foreach (DataTable table in dataSet.Tables)
                {
                    jsonString += "\"" + StringToJson(table.TableName) + "\":" + DatatableToJson(table)

                    + ",";
                }
                return jsonString = DeleteLast(jsonString) + "}";
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
       

        /// <summary>
        /// 根据模板 将datatable数据转换成json数据格式
        /// </summary>
        /// <param name="table">数据集</param>
        /// <param name="templateDT">模板dt</param>
        /// <returns></returns>
        public string DatatableToJsonByTemplate(DataTable table,DataTable templateDT)
        {
            int startX ;//从第几行开始去数据；
            try
            {
                startX = Convert.ToInt32(templateDT.Rows[0]["STARTX"].ToString())-1;
            }
            catch
            {
                startX = 0;
            }
            try
            {
                string jsonString = "[";
                DataRowCollection drc = table.Rows;
                for (int i = startX; i < drc.Count; i++)
                {
                    jsonString += "{";
                    //foreach (DataColumn column in templateDT.Columns)
                    for(int j = 0;j<templateDT.Rows.Count;j++)
                    {
                        jsonString += "\"" + StringToJson(templateDT.Rows[j]["LINK_COL"].ToString().ToUpper()) + "\":";
                            jsonString += "\"" + StringToJson(drc[i]

                            [Convert.ToInt32(templateDT.Rows[j]["STARTY"].ToString())-1].ToString()) + "\",";

                    }
                    jsonString = DeleteLast(jsonString) + "},";
                }
                return DeleteLast(jsonString) + "]";
            }
            catch (Exception ex)
            {

                return string.Empty;
            }
        }
        /// <summary>
        /// String转换为Json
        /// </summary>
        /// <param name="value">String对象</param>
        /// <returns>Json字符串 成功(JSON) 异常 string.Empty</returns>
        public string StringToJson(string value)
        {
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    return string.Empty;
                }

                string temstr;
                temstr = value;
                //temstr = temstr.Replace("{", "｛").Replace("}", "｝").Replace(":",

                //"：").Replace(",", "，").Replace("[", "【").Replace("]", "】").Replace(";",

                //"；").Replace("\n", "<br/>").Replace("\r", "");
                temstr = temstr.Replace("\n", "<br/>").Replace("\r", "");

                temstr = temstr.Replace("\t", " ");
                temstr = temstr.Replace("'", "\'");
                temstr = temstr.Replace(@"\", @"\\");
                temstr = temstr.Replace("\"", "\"\"");
                return temstr;
            }
            catch (Exception ex)
            {

                return string.Empty;
            }
        } 
    }
}
